import React, {useEffect, useRef, useState} from "react";
import {connect} from "umi";
import {useAccess} from '@umijs/max';
import {cloneDeep} from "lodash";
import {ActionType, PageContainer, ProTable} from '@ant-design/pro-components';
import {
    Button,
    Form,
    Space,
    message,
    Modal,
    Select,
    Table,
    Typography,
    Popconfirm,
    TableProps,
    InputNumber,
    Input
} from "antd";
import {MenuOutlined} from "@ant-design/icons";
import request from "@/utils/request";

const EditableCell = (props: any) => {
    const {
        editing,
        dataIndex,
        title,
        inputType,
        record,
        index,
        children,
        ...restProps
    } = props;
    console.log('EditableCellProps', props);
    const inputNode = inputType === 'number' ? <InputNumber min={0}/> : <Input/>;

    return (
        <td {...restProps}>
            {editing ? (
                <Form.Item
                    name={dataIndex}
                    style={{margin: 0}}
                    rules={[
                        {
                            required: true,
                            message: `请输入${title}!`,
                        },
                    ]}
                >
                    {inputNode}
                </Form.Item>
            ) : (
                children
            )}
        </td>
    );
};
const PileNewList: React.FC = (props: any) => {
    const {dispatch} = props;
    const [form] = Form.useForm();
    const access = useAccess();
    console.log('useAccess', access);
    const actionRef = useRef<ActionType>();
    const [selectedRowsState, setSelectedRows] = useState<any[]>([]);
    const [stationList, setList] = useState([])
    const [stationOpen, setOpen] = useState(false)
    const [tableData, setTableData] = useState([]);
    const [curPile, setCurPile] = useState({});
    const [submitLoading, setSubmitLoading] = useState(false)
    const [tableDataLoading, setTableLoading] = useState(false)
    const [tableDataLoading2, setTableLoading2] = useState(false)
    const [modalOpen, setModalOpen] = useState(false)
    const [editingKey, setEditingKey] = useState('');
    const isEditing = (record: any) => record.id === editingKey;
    const getParams = (curPile: any) => {
        setTableLoading(true);
        setCurPile({...curPile})
        request('/api1/chargePileParam/paramList',
            {method: 'post', data: {devAddr: curPile?.pileCode}}
        ).then((response) => {
            console.log('getParams', response);
            if (response && response.code === 200) {
                setTableData(response.data);
                setTableLoading(false)
                // setTimeout(() => setModalOpen(true), 500)
            } else {
                setTimeout(() => setTableLoading(false), 0)
            }
        });
        setTimeout(() => setModalOpen(true), 0)
    }
    const refreshParams = (curPile: any) => {
        setTableLoading2(true)
        request('/api1/chargePileParam/refresh', {
            method: 'post',
            data: {
                devAddr: curPile?.pileCode
            }
        }).then((res) => {
            console.log('refreshParams', res);
            if (res.code && res.code === 200) {
                setTableLoading2(false);
                message.success('刷新成功')
            } else {
                setTimeout(() => setTableLoading2(false), 500)
                message.warning('刷新失败')
            }
        })
    }
    const refreshSingleParams = (obj: any) => {
        setTableLoading2(true)
        request('/api1/chargePileParam/findParamByDevice', {
            method: 'post',
            data: {
                devAddr: curPile?.pileCode,
                paramFlag: obj?.paramFlag
            }
        }).then((res) => {
            console.log('refreshParams', res);
            if (res.code && res.code === 200) {
                setTableLoading2(false);
                message.success('刷新成功')
            } else {
                setTimeout(() => setTableLoading2(false), 500)
                message.warning('刷新失败')
            }
        })
    }
    const edit = (record: Partial<any>) => {
        form.setFieldsValue({name: '', age: '', address: '', ...record});
        setEditingKey(record.id);
    };

    const cancel = () => {
        setEditingKey('');
    };
    const save = async (obj: any) => {
        const {id} = obj;
        try {
            const row = (await form.validateFields()) as any;
            console.log('row', row);
            console.log('obj', obj);
            const newData: any = [...tableData];
            const index = newData.findIndex((item: any) => id === item.id);
            if (index > -1) {
                setSubmitLoading(true);
                request('/api1/chargePileParam/setParamByDevice', {
                    method: 'post',
                    data: {
                        ...obj,
                        paramValue: row?.paramValue.toString(),
                        devAddr: curPile.pileCode
                    }
                }).then((response) => {
                    console.log('设置参数', response);
                    if (response.code && response.code === 200) {
                        setTimeout(() => {
                            request('/api1/chargePileParam/paramList',
                                {method: 'post', data: {devAddr: curPile?.pileCode}}
                            ).then((response) => {
                                console.log('getParams', response);
                                if (response && response.code === 200) {
                                    setTableData(response.data);
                                    // const item = newData[index];
                                    // newData.splice(index, 1, {
                                    //     ...item,
                                    //     ...row,
                                    // });
                                    // setTableData(newData);
                                    setEditingKey('');
                                    setSubmitLoading(false);
                                }
                            })
                        }, 5000)
                    } else {
                        message.warning(response?.msg || '接口调用失败')
                    }
                })
            } else {
                newData.push(row);
                setTableData(newData);
                setEditingKey('');
            }
        } catch (errInfo) {
            console.log('Validate Failed:', errInfo);
        }
    };
    const columns = [
        {
            title: '变量标识',
            dataIndex: 'paramFlag',
            // width: '25%',
            editable: false,
            hidden: true,
        },
        {
            title: '数据类型',
            dataIndex: 'paramType',
            // width: '15%',
            editable: false,
            // hidden: true,
        },
        {
            title: '长度(字节)',
            dataIndex: 'paramLength',
            // width: '15%',
            editable: false,
            // hidden: true,
        },
        {
            title: '说明',
            dataIndex: 'paramName',
            // width: '40%',
            editable: false,
        },
        // paramValue
        {
            title: '参数值',
            dataIndex: 'paramValue',
            width: 160,
            // width: '40%',
            editable: true,
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: 126,
            render: (_: any, record: any) => {
                const editable = isEditing(record);
                return editable ? (
                    <span>
            <Typography.Link onClick={() => save(record)} style={{marginInlineEnd: 8}}>
              保存
            </Typography.Link>
            <Popconfirm title="确定取消编辑吗?" onConfirm={cancel}>
              <a>取消</a>
            </Popconfirm>
          </span>
                ) : (
                    <span>
                        <Typography.Link
                            disabled={editingKey !== ''}
                            onClick={() => edit(record)}
                            style={{marginInlineEnd: 8}}
                        >编辑</Typography.Link>
                        {
                            record?.paramRequest !== '只写' ? <Typography.Link
                                disabled={editingKey !== ''}
                                onClick={() => refreshSingleParams(record)}
                            >刷新参数</Typography.Link> : null
                        }
                    </span>
                );
            },
        },
    ];
    const mergedColumns: TableProps<any>['columns'] = columns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: any) => ({
                record,
                inputType: record.paramType === '整型' ? 'number' : 'text',
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });
    const hideModal = () => {
        setOpen(false);
        form.resetFields();
    }
    useEffect(() => {
        request('/api1/baseFunction/stationPageList', {
            method: 'post',
            data: {
                pageNum: 1,
                pageSize: 9999
            }
        }).then((res) => {
            console.log('全部站', res);
            if (res && res.code === 200) {
                setList(res?.data?.records || [])
            }
        })
    }, [dispatch]);
    const stationEnum: any = {};
    if (stationList && stationList.length) {
        for (const d of stationList) {
            stationEnum[d.id] = {text: d.stationName}
        }
    }
    console.log('stationEnum', stationEnum);
    const submitForm = (values: any) => {
        console.log('submitForm', values);
        console.log('stationList', stationList);
        request(
            '/api1/baseFunction/batchUpdatePileStationId',
            {
                method: 'POST',
                // requestType: 'form',
                data: {
                    ...values,
                    stationName: values?.stationId && stationList.length ?
                        stationList.find((i) => i.id === values.stationId)?.stationName : null,
                    ids: selectedRowsState.length ? selectedRowsState.map((i) => i.id).join(',') : []
                },
            }
        ).then((response) => {
            if (response && response.code === 200) {
                message.success('操作成功');
                if (actionRef.current) {
                    actionRef.current.reset();
                    setOpen(false);
                    // setSelectedRows([])
                    console.log(' actionRef.current', actionRef.current);
                    form.resetFields();
                }
            } else {
                message.warning(response?.msg)
            }
        })
    }
    const columnsOrigin: any = [
        {
            title: '桩编码',
            dataIndex: 'pileCode',
            key: 'pileCode',
        },
        {
            title: '枪数量',
            dataIndex: 'gunNum',
            key: 'gunNum',
            search: false,
        },
        {
            title: '所属场站',
            dataIndex: 'stationId',
            key: 'stationId',
            // search: false,
            valueEnum: stationEnum,
            render: (_, record) => {
                return (<span>{record?.stationName || ''}</span>)
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            search: false,
        },
        {
            title: '操作',
            dataIndex: 'ope',
            key: 'ope',
            search: false,
            align: 'center',
            render: (_, record) => {
                return (
                    <Space size="middle">
                        <a onClick={() => refreshParams(record)}>刷新参数</a>
                        <a onClick={() => getParams(record)}>设置参数</a>
                    </Space>
                )
            }
        }
    ]
    return (
        <PageContainer
            ghost
            header={{
                title: '',
            }}
        >
            <ProTable<API.UserInfo>
                loading={tableDataLoading2}
                headerTitle="桩列表"
                actionRef={actionRef}
                rowKey="id"
                pagination={{defaultPageSize: 10}}
                search={{
                    labelWidth: 120,
                }}
                toolBarRender={() => [,
                    <Button
                        disabled={!selectedRowsState.length}
                        type="primary"
                        icon={<MenuOutlined/>}
                        onClick={() => {
                            setOpen(true);
                            // form.setFieldValue('effectTime2', [null, null])
                        }}
                    >
                        批量设置场站
                    </Button>
                ]}
                request={async (params, sorter, filter) => {
                    // const { data, success } = await queryUserList({
                    //   ...params,
                    //   // FIXME: remove @ts-ignore
                    //   // @ts-ignore
                    //   sorter,
                    //   filter,
                    // });
                    // return {
                    //   data: data?.list || [],
                    //   success,
                    // };
                    const cloneParams = cloneDeep(params);
                    delete cloneParams.current;
                    const {data, code} = await request('/api1/baseFunction/pilePageList', {
                        method: 'post',
                        data: {
                            ...cloneParams,
                            pageNum: params.current
                        }
                    });
                    console.log('data', data);
                    if (code && code === 200) {
                        return {
                            data: data?.records || [],
                            success: true,
                            total: data?.total
                        };
                    }
                }}
                columns={columnsOrigin}
                rowSelection={{
                    onChange: (_, selectedRows) => {
                        setSelectedRows(selectedRows);
                    },
                }}
            />
            <Modal
                title="设置场站"
                open={stationOpen}
                width={680}
                onOk={form.submit}
                onCancel={hideModal}
                maskClosable={false}
                okText="确认"
                cancelText="取消"
            >
                <Form
                    labelCol={{span: 4}}
                    wrapperCol={{span: 14}}
                    layout="horizontal"
                    form={form}
                    style={{maxWidth: 600}}
                    onFinish={(values) => submitForm(values)}
                >
                    <Form.Item
                        label="适用场站"
                        name="stationId"
                        rules={[{required: true, message: '请选择场站'}]}
                    >
                        <Select
                            showSearch
                            placeholder="请选择场站"
                            optionFilterProp="label"
                            // onChange={onChange}
                            // onSearch={onSearch}
                            options={
                                stationList.length ?
                                    stationList.map((i) => {
                                        return {value: i.id, label: i.stationName}
                                    }) : []
                            }
                        />
                    </Form.Item>
                </Form>
            </Modal>
            <Modal
                open={modalOpen}
                title='充电桩参数设置'
                width={800}
                footer={null}
                onCancel={() => setModalOpen(false)}
            >
                <Form form={form} component={false}>
                    <div style={{width: '100%', marginBottom: 12, display: 'flex', justifyContent: 'flex-end'}}>
                        <Button type='primary' onClick={() => refreshParams(curPile)}>刷新参数</Button>
                    </div>
                    <Table<any>
                        components={{
                            body: {cell: EditableCell},
                        }}
                        bordered
                        loading={tableDataLoading || submitLoading || tableDataLoading2}
                        dataSource={tableData}
                        columns={mergedColumns}
                        rowClassName="editable-row"
                        rowKey='id'
                        pagination={false}
                        scroll={{y: 500}}
                    />
                </Form>
            </Modal>
        </PageContainer>
    );
};

export default connect(({files}) => {
    return {...files}
})(PileNewList);
